<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Model\HomeUserModel;
use App\Model\HomeUserScores;
use App\Model\HomeUserBeforpass;
use App\Model\HomeUserMemberExp;
use App\Http\Requests\addUservalidata;
use App\Http\Requests\updateUservalidata;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\CommonApi;
use Illuminate\Support\Facades\Redis;
use DB, Validator;

/**
 *
 *黎子聪
 *
 */
class MemberList extends Controller
{

    protected $password;

    /**
     * 显示用户列表页
     * 黎子聪
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // 得到搜索框内容
        $search = $request->input('search');
        // 判断是否搜索
        if (empty($search)) {
            $where = [];
        }

        // 搜索准备条件
        $where = [['username', 'like', "%$search%"]];

        // 查询
        $users = HomeUserModel::select('id', 'sex', 'username', 'phone', 'email', 'user_status', 'created_at')->where($where)->paginate(5);

        // 返回视图层
        return view('Admin.member.member-list', ['users' => $users, 'search' => $search]);
    }

    /**
     *
     * 显示添加用户页面
     * 黎子聪
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        // 返回视图层
        return view('Admin.member.member-add');

    }

    /**
     * 处理添加用户信息
     * 黎子聪
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(addUservalidata $request)
    {
        // new图片上传类
        $api = new CommonApi;
        $user = new HomeUserModel;

        // 获取填写的数据
        $username = $request->input('username');
        $password = $request->input('password');
        $sex      = $request->input('sex');
        $phone    = $request->input('phone');
        $picurl   = $request->input('picurl');

        // 拿出文件后缀
        $suffix = ltrim(strrchr($picurl, '.'), '.');

        // 拿出文件名
        $test = ltrim(strrchr($picurl, '\\'), '\\');

        // 图片类型集合
        $suffixset = ['image', 'png', 'jpg', 'img','jpeg', 'gif'];

        // 判断后缀是否为图片类型
        $filesuffix = in_array($suffix, $suffixset);

        // 判断是否上传
        if ($request->file) {
            // 判断是否图片
            if (!$filesuffix) {
                return redirect()->route('member.create')->with('message', '上传文件不合法');
            }

            // 上传图片
            $picname = $api->uploadToQiNiu($request, 'file');

            // 判断图片是否上传成功
            switch($picname['status']) {
                case '4044':
                    return redirect()->route('member.create')->with('message', '服务器繁忙');
                break;

                case '4403':
                    return redirect()->route('member.create')->with('message', '没有上传文件');
                break;
            }
        }

        // 判断是否上传成功
        if (!isset($picname)) {
            $picname = '150941484559f7d7bd7092b.jpg';
        } else {
            $picname = $picname['data']['key'];
        }

        // 添加用户
        $user = HomeUserModel::insert(
            [
                'username'   => $username,
                'passname'   => password_hash($password, PASSWORD_DEFAULT),
                'sex'        => $sex,
                'phone'      => $phone,
                'pic'        => $picname,
                'created_at' => date('Y-m-d h:i:s'),
            ]
        );

        // 判断用户是否添加成功
        if ($user) {

            // 获取用户id
            $user_id = HomeUserModel::select('id')->where('phone', $phone)->get();

            // 给该用户添加对应的会员经验表
            HomeUserMemberExp::insert(
                [
                    'user_id'  => $user_id[0]->id,
                ]
            );

            // 给该用户添加对应的积分表
            $result = HomeUserScores::insert(
                  [
                      'user_id' => $user_id[0]->id,
                      'scores'  => '0',
                  ]
              );

            // 创建成功返回提示
                return redirect()->route('member.create')->with('message', '创建成功');
        }


        // 创建失败放回提示
        return redirect()->route('member.create')->with('message', '服务器繁忙');
    }

    /**
     * 显示详情页
     * 黎子聪
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        // 获取该用户信息
        $user = HomeUserModel::find($id);
        $result = $user->scores;
        // 返回视图层
        return view('Admin.member.member-show', ['user' => $user]);
    }

    /**
     * 显示编辑页面
     * 黎子聪
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        // 获取该用户信息
        $user = HomeUserModel::find($id);

        // 返回视图层
        return view('Admin.member.member-edit', ['user' => $user]);
    }

    /**
     * 处理编辑方法
     * 黎子聪
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(updateUservalidata $request, $id)
    {

        // new图片上传类
        $api = new CommonApi;

        // 判断是否上传
        if ($request->file) {
            // 准备图片数据
            $picurl = $request->input('picurl');

            // 拿出文件后缀
            $suffix = ltrim(strrchr($picurl, '.'), '.');

            // 拿出文件名
            $test = ltrim(strrchr($picurl, '\\'), '\\');

            // 图片类型集合
            $suffixset = ['image', 'png', 'jpg', 'img','jpeg', 'gif'];

            // 判断后缀是否为图片类型
            $filesuffix = in_array($suffix, $suffixset);

            // 判断是否图片
            if (!$filesuffix) {
                return redirect()->route('member.edit', ['id' => $id])->with('message', '上传文件不合法');
            }

            // 上传图片
            $picname = $api->uploadToQiNiu($request, 'file');

            // 判断图片是否上传成功
            switch($picname['status']) {
                case '4044':
                    return redirect()->route('member.edit', ['id' => $id])->with('message', '服务器繁忙');
                break;

                case '4403':
                    return redirect()->route('member.edit', ['id' => $id])->with('message', '没有上传文件');
                break;
            }
        }

        // 判断是否上传成功
        if (!isset($picname)) {
            $picname = '150941484559f7d7bd7092b.jpg';
        } else {
            $picname = $picname['data']['key'];
        }

        // 判断邮箱是否为空
        if ($request->email) {
            // 表单验证
            $this->validate($request, [
                'email' => [
                    'email',
                    'required',
                    Rule::unique('shop_home_users')->ignore($id),
                ],
                'phone' => [
                    'required',
                    'regex:/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/u',
                    Rule::unique('shop_home_users')->ignore($id),
                ],
            ],[
                'email.email'    => '邮箱格式不正确',
                'email.required' => '邮箱不能为空',
                'email.unique'   => '邮箱已注册',
                'phone.required' => '手机号不能为空',
                'phone.regex'    => '手机号格式不正确',
                'phone.unique'   => '手机号已注册',
            ]);
        }


        // 取出用户信息
        $userinfo = HomeUserModel::find($id);
        // 修改数据
        $result = HomeUserModel::where('id', $id)
        ->update([
          'username' => $request->input('username'),
          'sex'      => $request->input('sex'),
          'member'   => $request->input('member'),
          'phone'    => $request->input('phone'),
          'email'    => $request->input('email'),
          'pic'      => $picname,
        ]);

        // 准备redis键名
        $userkey = 'home_user_hash_phone:'.$userinfo->phone;

        // 查询redis是否有该用户
        $redisuser = Redis::hGetAll($userkey);

        // 如果有就更改redis用户状态
        if ($redisuser) {
            Redis::del($userkey);
            $userinfo = Redis::hMSet($userkey, [
                'id'         => $userinfo->id,
                'username'   => $request->input('username'),
                'passname'   => $userinfo->passname,
                'sex'        => $request->input('sex'),
                'pic'        => $picname,
                'email'      => $request->input('email'),
                'phone'      => $request->input('phone'),
                'user_status'=> $userinfo->user_status,
                'member'     => $request->input('member'),
                'created_at' => $userinfo->createtime,
            ]);
        }

        // 修改成功返回信息
        return redirect()->route('member.edit', ['id' => $id])->with('message', '修改成功');

        // 修改失败返回信息
        return redirect()->route('member.edit', ['id' => $id])->with('message', '修改失败');
    }


    /**
     *
     * 黎子聪
     * @param  int  $id
     * 删除用户处理方法
     */
    public function delete($id)
    {
        // 找到用户
        $user = HomeUserModel::find($id);

        // 准备键名
        $userkey = 'home_user_hash_phone:'.$user->phone;
        // 找到redis中用户信息
        $redisuser = Redis::hGetAll($userkey);

        // 如果有就更改redis用户状态
        if ($redisuser) {
            Redis::del($userkey);
        }

        HomeUserMemberExp::where('user_id', $id)->delete();

        // 给该用户添加对应的积分表
        HomeUserScores::where('user_id', $id)->delete();

        // 删除用户
        $user->delete();
    }

    /**
     * 显示修改密码页面
     */
    public function showchangepass($id)
    {
        $user = HomeUserModel::find($id);

        return view('Admin.member.member-changepass', ['user' => $user]);
    }

    /**
     * 处理修改密码方法
     */
    public function dochangepass(Request $request)
    {
        // 查出该用户信息
        $user = HomeUserModel::select('passname')->where('id', $request->id)->first();

        // 表单验证
        $this->validate($request, [
          'password'              => 'required|confirmed|min:6',
          'password_confirmation' => 'required',
        ],[
          'password_confirmation.required' => '确认密码不能为空',
          'password_confirmation.min'      => '密码不能少于6位',
          'password.required'              => '密码不能为空',
          'password.min'                   => '密码不能少于6位',
          'password.confirmed'             => '两次密码内容不相同',
        ]);

        // 记录过去密码
        HomeUserBeforpass::insert([
          'user_id'    => $request->id,
          'befor_pass' => $user->passname,
        ]);

        // 更改密码
        HomeUserModel::where('id', $request->id)
        ->update([
              'passname' => password_hash($request->input('password'), PASSWORD_DEFAULT),
        ]);

        // 准备键名
        $userkey = 'home_user_hash_phone:'.$user->phone;

        // 查询redis是否有该用户
        $redisuser = Redis::hGetAll($userkey);

        // 如果有就更改redis用户状态
        if ($redisuser) {
            Redis::del($userkey);
            $userinfo = Redis::hMSet($userkey, [
                'id'         => $user->id,
                'username'   => $user->username,
                'passname'   => password_hash($request->input('password'), PASSWORD_DEFAULT),
                'sex'        => $user->sex,
                'pic'        => $user->pic,
                'email'      => $user->email,
                'phone'      => $user->phone,
                'user_status'=> $user->user_status,
                'member'     => $user->member,
                'created_at' => $user->createtime,
            ]);
        }

        return redirect()->route('member.changepass', ['id' => $request->id])->with('message', '修改成功');

    }

    /**
     *
     * 黎子聪
     * 用户状态改为禁用
     */
    public function stop(Request $request)
    {
        // 找到用户信息
        $user = HomeUserModel::find($request->id);

        // 根据带过来的id更改用户状态为禁用
        $result = DB::table('shop_home_users')->where('id', $user->id)->update(['user_status' => 0]);

        // 准备redis键名
        $userkey = 'home_user_hash_phone:'.$user->phone;

        // 查询redis是否有该用户
        $redisuser = Redis::hGetAll($userkey);

        // 如果有就更改redis用户状态
        if ($redisuser) {
            Redis::del($userkey);
            $userinfo = Redis::hMSet($userkey, [
                'id'         => $user->id,
                'username'   => $user->username,
                'passname'   => $user->$passname,
                'sex'        => $user->sex,
                'pic'        => $user->pic,
                'email'      => $user->email,
                'phone'      => $user->phone,
                'user_status'=> '0',
                'member'     => $user->member,
                'created_at' => $user->createtime,
            ]);
        }

    }

    /**
     *
     * 黎子聪
     * 用户状态改为启用
     */
    public function start(Request $request)
    {
        // 找到用户信息
        $user = HomeUserModel::find($request->id);

        // 根据带过来的id更改用户状态为启用
        $result = DB::table('shop_home_users')->where('id', $user->id)->update(['user_status' => 1]);

        // 准备redis键名
        $userkey = 'home_user_hash_phone:'.$user->phone;

        // 查询redis是否有该用户
        $redisuser = Redis::hGetAll($userkey);

        // 如果有就更改redis用户状态
        if ($redisuser) {
            Redis::del($userkey);
            $userinfo = Redis::hMSet($userkey, [
                'id'         => $user->id,
                'username'   => $user->username,
                'passname'   => $user->passname,
                'sex'        => $user->sex,
                'pic'        => $user->pic,
                'email'      => $user->email,
                'phone'      => $user->phone,
                'user_status'=> '1',
                'member'     => $user->member,
                'created_at' => $user->createtime,
            ]);
        }

    }
}
